package com.cs.rabbittest.demo;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * RabbitMQ 生产者
 *
 * @author
 */
public class Producer01 {
    private static final String QUEUE = "helloworld";

    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = null;
        Channel channel = null;
        try {
            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost("localhost");
            factory.setPort(5672);
            factory.setUsername("guest");
            factory.setPassword("guest");
            // rabbit默认的虚拟机名称是"/", 虚拟机相当于一个独立的MQ服务器
            factory.setVirtualHost("/");
            // 创建与rabbitMQ的TCP连接
            connection = factory.newConnection();
            // 创建与Exchange的通道，每个连接可以创建多个通道，每个通道代表一个会话任务
            channel = connection.createChannel();
            /**
             * @param queue the name of the queue
             * @param durable 是否持久化
             * @param exclusive 队列是否独占此连接， true if we are declaring an exclusive queue (restricted to this connection)
             * @param autoDelete 队列不再使用时是否自动删除此队列，true if we are declaring an autodelete queue (server will delete it when no longer in use)
             * @param arguments other properties (construction arguments) for the queue
             */
            channel.queueDeclare(QUEUE, true, false, false, null);
            /**
             * 消息发布方法
             @param exchange the exchange to publish the message to
              * @param routingKey 消息的路由key，是用于Exchange将消息转发到指定的消息队列 the routing key
             * @param props 消息包含的属性， other properties for the message - routing headers etc
             * @param body  消息体 the message body
             */
            /**
             * 这里没指定交换机，消息将发送给默认的交换机， 每个队列也会绑定那个默认的交换机，
             * 但是不能显示绑定或解除绑定
             * 默认的交换机，routingkey等于队列的名称
             */
            for (int i = 0; i < 10; i++) {
                String message = String.format(" 宝欣2 %s", System.currentTimeMillis());
                channel.basicPublish("", QUEUE, null, message.getBytes());
            }
        } catch (TimeoutException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (channel != null) {
                channel.close();
            }
            if (connection != null) {
                connection.close();
            }

        }
    }
}
